<!-- 饼图 -->
<template>
  <div style="width: 100%;">
    <!-- <div class="title">
      <p>{{ title }}</p>
    </div> -->
    <div ref="piechart" id="chart" :style="{ height: height, width: width }"></div>
  </div>
</template>

<script>
require('echarts/theme/macarons') // echarts theme
import Cookies from 'js-cookie'
import { connrequest } from "@/api/firstPage";
import { parseTime } from "@/utils/index.js";
import { formatDuration } from "@/utils/index.js";
export default {
  data() {
    return {
      chartData: []
    };
  },
  props: {
    title: {
      type: String,
      default: "综合统计数据分析"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "350px"
    },
    tooltip: {
      type: String,
      default: "数量"
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() { },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.Moder = JSON.parse(sessionStorage.getItem('detailStatus'))
    this.GetDNSSumByMainClass()
  },
  methods: {
    async GetDNSSumByMainClass(searchobj = {}) {
      let arr = []
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      const data = {
        Filter: {
          StartTime: parseTime(startTime),
          EndTime: '',
          DeviceUUID: this.Moder.DeviceUUID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetDNSSumByMainClass', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ name: item.MainClass || '未知分类', value: item.Count || 0 })
      })
      this.chartData = arr
      this.$nextTick(() => {
        this.setOptions(arr)
      })
    },
    setOptions(chartData) {
      let that = this
      var showData = []
      var sum = 0, max = 0;
      chartData.forEach(item => {
        sum += item.value
        if (item.value >= max) max = item.value
      })
      // 放大规则
      var number = Math.round(max * 0.1)
      // var number = 0
      showData = chartData.map(item => {
        return {
          value: number + item.value,
          name: item.name,
          id: item.id,
          num: item.value,
          ...item
        }
      })
      this.myChart = this.$echarts.init(this.$refs.piechart);
      this.myChart.setOption({
        title: {
          left: "center"
        },
        tooltip: {
          trigger: "item",
          backgroundColor: '#fff',
          formatter: function (param) {
            return `${param.marker}${param.name}<b style="margin-left:20px">${that.title.indexOf('使用时长') !== -1 ? formatDuration(param.data.num) : param.data.num}</b>`
          }
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          width: 70,
          textStyle: {
          },
          formatter: function (name) {
            //通过name获取到数组对象中的单个对象
            let singleData = chartData.filter(function (item) {
              return item.name == name
            })
            return `${name} ( ${that.title.indexOf('使用时长') !== -1 ? formatDuration(singleData[0].value) : singleData[0].value} )`;
          }
        },
        series: [
          {
            type: "pie",
            roseType: 'area',
            radius: [20, 120],
            data: showData,
            label: {
              normal: {
                show: true,
                formatter: function (param) {
                  return param.name + ' (' + (`${that.title.indexOf('使用时长') !== -1 ? formatDuration(param.data.num) : param.data.num}`) + ')'
                }
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0
              }
            },
          }
        ]
      });
      this.myChart.off('click');
      this.myChart.on('click', (params) => {
        this.$emit('pieclick', params.name ? params.name : 'NULL', this.title, params.data.id, params.data)
      });
    }
  }
};
</script>
<style scoped></style>